package com.tencent.qf.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.tencent.qf.common.pojo.HttpResult;
import com.tencent.qf.mybatis.pojo.PageRequest;
import com.tencent.qf.mybatis.pojo.PageResult;
import lombok.Data;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class QueryZhiyanAndCheckApi {

    public static void main(String[] args) throws IOException {
        // 设置默认工厂类
        System.setProperty("org.apache.commons.logging.LogFactory", "org.apache.commons.logging.impl.LogFactoryImpl");
        // 设置日志打印类
        LogFactory.getFactory().setAttribute("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
        //设置默认日志级别
        LogFactory.getFactory().setAttribute("org.apache.commons.logging.simplelog.defaultlog", "error");

        long start = LocalDateTime.parse("2022-11-30 08:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).toInstant(ZoneOffset.of("+8")).toEpochMilli();
        long end = LocalDateTime.parse("2022-11-30 23:59:59", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).toInstant(ZoneOffset.of("+8")).toEpochMilli();

        String zhiyanRequestJson = "{\n" +
                "    \"startTime\": " + start + ",\n" +
                "    \"endTime\":  " + end + ",\n" +
                "    \"indexName\": \"data_handle_prod_nginx_logs\",\n" +
                "    \"query\": \"request_uri: /.*guiderSharePaginate/\",\n" +
                "    \"from\": 1,\n" +
                "    \"size\": 50,\n" +
                "    \"fields\": \"request_body,res_body,@timestamp\"\n" +
                "}";
        String requestJson = getZhiYanLog(zhiyanRequestJson);
        requestJson = requestJson.replaceAll("@timestamp", "timestamp");

        String url = "http://open-dev.local.woa.com/api/team/guiderSharePaginate";
        Res res = JSON.parseObject(requestJson, new TypeReference<Res>() {
        });

        if (CollectionUtils.isEmpty(res.getData().getData())) {
            System.out.println("智妍日志获取条数:0");
            return;
        }
        System.out.println("智妍日志获取条数：" + res.getData().getData().size());

        Integer i = 0;
        Integer s = 0;
        Integer f = 0;
        for (Da e : res.getData().getData()) {
            String request_body = e.getRequest_body();
            String res_body = e.getRes_body();
            String request = lineToHump(request_body);
            String zhiyan = lineToHump(res_body);

            if(zhiyan == null || !zhiyan.endsWith("}")){
                System.out.println("日志截断");
                continue;
            }

//            // 查询分页
            HashMap hashMap = JSON.parseObject(request, new TypeReference<HashMap>() {});
            PageRequest pageRequest = new PageRequest();
            pageRequest.setPageNo(Integer.valueOf(hashMap.get("page").toString()));
            pageRequest.setPageSize(Integer.valueOf(hashMap.get("perPage").toString()));
            pageRequest.setData(hashMap);
            request = JSON.toJSONString(pageRequest);

////             /api/team/sharerOutOrderSum
////             /api/team/guiderOrderCpsPersonalTotal
////             /api/team/guiderOrderCpsPaginate 日志截断
////             /api/team/guiderOrderGoodsCpsPaginate 日志截断
////             /api/team/commdityCoupons/validUniqueIdList


            if (i == 0) {
                System.out.println("请求参数：" + request);
            }
            String apires = null;
            try {
                apires = httpPostSend(url, request);
            } catch (IOException ex) {
                System.out.println("第" + i + "条失败");
                ex.printStackTrace();
                break;
            }

//            //查询object
//            HttpResult<HashMap> zhiyanJson = JSON.parseObject(zhiyan, new TypeReference<HttpResult<HashMap>>() {});
//            HttpResult<HashMap> result = JSON.parseObject(apires, new TypeReference<HttpResult<HashMap>>() {});
//            zhiyan = JSON.toJSONString(zhiyanJson.getData());
//            apires = JSON.toJSONString(result.getData());

//            //查询list
//            HttpResult<List<HashMap>> zhiyanJson = JSON.parseObject(zhiyan, new TypeReference<HttpResult<List<HashMap>>>() {
//            });
//            HttpResult<List<HashMap>> result = JSON.parseObject(apires, new TypeReference<HttpResult<List<HashMap>>>() {
//            });
//            zhiyan = JSON.toJSONString(zhiyanJson.getData());
//            apires = JSON.toJSONString(result.getData());

//            // 查询分页
//            HttpResult<HashMap<String,List<HashMap>>> zhiyanJson = JSON.parseObject(zhiyan, new TypeReference<HttpResult<HashMap<String,List<HashMap>>>>() {});
            HttpResult<PageResult<HashMap>> zhiyanJson = JSON.parseObject(zhiyan, new TypeReference<HttpResult<PageResult<HashMap>>>() {});
            HttpResult<PageResult<HashMap>> result = JSON.parseObject(apires, new TypeReference<HttpResult<PageResult<HashMap>>>() {});
            zhiyan = JSON.toJSONString(zhiyanJson.getData().getList());
            apires = JSON.toJSONString(result.getData().getList());

            if (!zhiyan.equals(apires)) {
                System.out.println();
                System.out.println("第" + i + "条结果不匹配");
                System.out.println(zhiyan);
                System.out.println(apires);
                System.out.println("请求参数：" + request);
                System.out.println();
                f++;
                i++;
                continue;
            }
            System.out.println("第" + i + "条匹配成功");
            i++;
            s++;
        }
        System.out.println("成功条数：" + s);
        System.out.println("失败条数：" + f);
    }

    private static String getZhiYanLog(String zhiyanRequestJson) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost("http://openapi.zhiyan.oa.com/log/search");
        httpPost.setHeader("projectname", "jjjtech");
        httpPost.setHeader("token", "f2e7a23fa758cd9f0fe1070bcf29031b");
        httpPost.setHeader("x-api-version", "v1");
        httpPost.setHeader("staffname", "delanhuang");
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setEntity(new StringEntity(zhiyanRequestJson, "UTF-8"));
        CloseableHttpResponse response = httpClient.execute(httpPost);

        // Receive response
        HttpEntity responseEntity = response.getEntity();
        if (responseEntity != null) {
            String result = EntityUtils.toString(responseEntity);
            return result;
        } else {
            System.out.println("error:" + JSON.toJSONString(response));
        }
        return null;
    }

    private static String httpPostSend(String url, String request) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // Send request
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("linkToProdDB", "true");
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setEntity(new StringEntity(request, "UTF-8"));
        CloseableHttpResponse response = httpClient.execute(httpPost);

        // Receive response
        HttpEntity responseEntity = response.getEntity();
        if (responseEntity != null) {
            String result = EntityUtils.toString(responseEntity);
            return result;
        } else {
            System.out.println("error:" + JSON.toJSONString(response));
        }
        return null;
    }

    private static Pattern linePattern = Pattern.compile("_(\\w)");

    /**
     * 下划线转驼峰
     */
    public static String lineToHump(String str) {
        str = str.toLowerCase();
        Matcher matcher = linePattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    @Data
    public static class Res {
        private String code;
        private String msg;
        private String request_id;
        private Dat data;
    }

    @Data
    public static class Dat {
        private Integer total;
        private Integer totalPage;
        private List<Da> data;
    }

    @Data
    public static class Da {
        private String res_body;
        private String request_body;
        private String timestamp;
    }


}
